/*
包含多个间接改变state的方法的对象
*/

import {REQUESTING, REQ_SUCCESS, REQ_ERROR} from './mutatiosn_types'
import axios from 'axios'

export default {
  async search({commit}, searchName) {
    // 点击按钮搜索第一次的状态
    commit(REQUESTING)

    try {
      // 发送请求
      const response = await axios.get('https://api.github.com/search/users', {
        params: {
          q: searchName
        }
      })
      // 请求成功时
      const result = response.data
      const users = result.items.map(item => ({
        username: item.login,
        url: item.html_url,
        avatar_url: item.avatar_url
      }))
      commit(REQ_SUCCESS, {users})
    } catch (error) {
      const msg = error.message
      commit(REQ_ERROR, {msg})
    }
  }
}